﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Ports;
using SerialPortHelperLib;
using XChip_Common;
using XChipTool.Enties;
using System.Configuration;
using BinAnalysisHelp;

namespace XChipTool
{
    public partial class XChip_Lite_Snr : DevExpress.XtraEditors.XtraUserControl
    {

        public SerialPort sPortTemp;
        private bool isRead = false;
        private bool isWrite = false;
        private KeyEventArgs keyEnter = new KeyEventArgs(Keys.Enter);//用来手动触发文本框下发配置
        List<string> listfiltration = new List<string> { "slope", "scale_sigma", "scale_nr" };
        public parameter_exportManager Pe_dal { get; private set; }
        private addressregisterManager aBll;
        private List<addressregister> XChipSnr;
        private List<addressregister> XChipDnr;
        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;

        public XChip_Lite_Snr()
        {
            InitializeComponent();
        }
        public XChip_Lite_Snr(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            sPortTemp = _sPortTemp;
            aBll = _aBll;
            XChipSnr = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "SNR" ));
            XChipDnr = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "DNR" ));
            InitializeComponent();
        }

        private void XChip_Reg_Snr_Load(object sender, EventArgs e)
        {
            Task.Run(() => {
            this.Invoke((EventHandler)delegate {
                for (int i = 0; i < XChipSnr.Count; i++)
                {

                    var type =AppHelper.NameTypeToString( XChipSnr[i].NameType);
                    var col = this.Controls.Find(type, true);


                    foreach (var item in col)
                    {
                        if (item is TextEdit)
                        {
                            //声明一个SuerToolTip
                            DevExpress.Utils.SuperToolTip graduationBatchSuperToolTip = new DevExpress.Utils.SuperToolTip();
                            //声明一个ToolTipTitleItem,保存标题
                            DevExpress.Utils.ToolTipTitleItem toolTipTitleItem = new DevExpress.Utils.ToolTipTitleItem();
                            String tooltips = "";

                            if (!string.IsNullOrEmpty(XChipSnr[i].Bit_Wide))
                            {
                                tooltips += $"位宽={XChipSnr[i].Bit_Wide}";
                            }
                            if (!string.IsNullOrEmpty(XChipSnr[i].Bit_Accuracy))
                            {
                                tooltips += $"|精度={XChipSnr[i].Bit_Accuracy}";
                            }
                            //设置标题文字
                            toolTipTitleItem.Text = tooltips;
                            //把标题添加到SuerToolTip
                            graduationBatchSuperToolTip.Items.Add(toolTipTitleItem);
                            //指定控件的SuperTip
                            ((TextEdit)item).SuperTip = graduationBatchSuperToolTip;
                            //正则判断
                            ((TextEdit)item).Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                            ((TextEdit)item).Properties.Mask.EditMask = BitsHelp.GetBitsToMask(XChipSnr[i].Bits, XChipSnr[i].Bit_Wide, XChipSnr.Where(c => c.NameType.ToLower().Contains(type) && c.ControlType == "0").Select(c => c.Bits).ToList());
                        }
                    }
                }
            });
            });
        }

        

        private void dir_nd_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            
            if (XChipSnr.Exists(c => c.NameType.ToLower() == $"dir_nd_en".ToLower()))
            {
                var model = XChipSnr.Find(c => c.NameType.ToLower() == $"dir_nd_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), dir_nd_en.Checked);
                SetSNRRegister(model, Val);
            }
        }

        private void dir_pd_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
             
            if (XChipSnr.Exists(c => c.NameType.ToLower() == $"dir_pd_en".ToLower()))
            {
                var model = XChipSnr.Find(c => c.NameType.ToLower() == $"dir_pd_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), dir_pd_en.Checked);
                SetSNRRegister(model, Val);
            }
        }

        private void dir_h_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            
            if (XChipSnr.Exists(c => c.NameType.ToLower() == $"dir_h_en".ToLower()))
            {
                var model = XChipSnr.Find(c => c.NameType.ToLower() == $"dir_h_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), dir_h_en.Checked);
                SetSNRRegister(model, Val);
            }
        }

        private void dir_v_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            
            if (XChipSnr.Exists(c => c.NameType.ToLower() == $"dir_v_en".ToLower()))
            {
                var model = XChipSnr.Find(c => c.NameType.ToLower() == $"dir_v_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), dir_v_en.Checked);
                SetSNRRegister(model, Val);
            }
        }

        private void block_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
           
            //var readVal = SerialSend.ReadRegister(Convert.ToUInt32(XChipSnr.Find(c => c.NameType.ToLower() == $"block_en".ToLower()).Address, 16), sPortTemp);
            //var t = (ulong)(block_en.Checked ? (readVal | 0x10) : (readVal & 0xef));

            if (XChipSnr.Exists(c => c.NameType.ToLower() == $"block_en".ToLower()))
            {
                var model = XChipSnr.Find(c => c.NameType.ToLower() == $"block_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), block_en.Checked);
                SetSNRRegister(model, Val);
            }
        }

        private void pixel_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            //var readVal = GetSNRRegister("pixel_en");
            //var readVal = SerialSend.ReadRegister(Convert.ToUInt32(XChipSnr.Find(c => c.NameType.ToLower() == $"inc_en".ToLower()).Address, 16), sPortTemp);
             
            if (XChipSnr.Exists(c => c.NameType.ToLower() == $"pixel_en".ToLower()))
            {
                var model = XChipSnr.Find(c => c.NameType.ToLower() == $"pixel_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), pixel_en.Checked);
                SetSNRRegister(model, Val);
            }
        }

        private void snr_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            
            if (XChipSnr.Exists(c => c.NameType.ToLower() == $"snr_en".ToLower()))
            {
                var model = XChipSnr.Find(c => c.NameType.ToLower() == $"snr_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), snr_en.Checked);
                SetSNRRegister(model, Val);
            }
        }

        private void inc_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            
            if (XChipSnr.Exists(c => c.NameType.ToLower() == $"inc_en".ToLower()))
            {
                var model = XChipSnr.Find(c => c.NameType.ToLower() == $"inc_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), inc_en.Checked);
                SetSNRRegister(model, Val);
            }
        }


        private long GetSNRRegister(string nameType)
        { 

            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return -1;
            }

            if (XChipSnr.Exists(c => c.NameType.ToLower() == nameType.ToLower()))
            {
                var model = XChipSnr.Find(c => c.NameType.ToLower() == nameType.ToLower());
                var Val = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                if (model.ControlType.Contains("1"))
                {
                    return BitsHelp.GetBitsCheckedToBool(model.Bits, model.Hex, Val.ToString("X2"));
                }
                else
                {
                    return BitsHelp.GetBitsToUint(model.Bits, model.Hex, Val.ToString("X2"));
                }
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }
        }
        private void SetSNRRegister(addressregister model, ulong add, bool isCheck = true)
        {
            if (IsUsbOpen)
            {
                if (null != BinHelp.usbList)
                {
                    uint pVule = 0x0;
                    var isbool = false;
                    if (IntPtr.Size == 8)
                    {
                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                    }
                    else
                    {
                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                    var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                    var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                    BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, model.Address, add.ToString("X"), chang, kuang);
                }
            }
            else if (m_open)
            {

            }
            else
            {
                if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                    return;
                }
                if (isRead) return;
                
                if (null != BinHelp.lspList)
                { //编写Bin更新数据
                    var temp = SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                    BinHelp.SetBinUpdateData(ref BinHelp.BinList, model.Address, add.ToString("X"), (uint)temp);
                }
            }
            SerialSend.WriteRegister(Convert.ToUInt32(model.Address, 16), add, sPortTemp);
            //if (XChipSnr.Exists(c => c.NameType == nameType))
            //{
            //    SerialSend.WriteRegister(Convert.ToUInt32(XChipSnr.Where(c => c.NameType == nameType).First().Address, 16), add, sPortTemp);
            //}
        }

        private void inc_shift_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(inc_shift.Text)) {
                //var nHigh = Convert.ToUInt32(inc_shift.Text, 16);
                //SetSNRRegister("inc_shift", (ulong)nHigh);
                if (XChipSnr.Exists(c => c.NameType.ToLower() == $"inc_shift".ToLower()))
                {
                    var model = XChipSnr.Find(c => c.NameType.ToLower() == $"inc_shift".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, inc_shift.Text);
                    if (Convert.ToUInt32(inc_shift.Text, 16)>Val)
                    {
                        inc_shift.Text = Val.ToString("X");
                    }
                    SetSNRRegister(model, Val);
                }
            }
        }

        private void inc_shift_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            inc_shift_KeyDown(sender, keyEnter);
        }

        private void inc_wave_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(inc_wave.Text))
            {
                var nHigh = Convert.ToUInt32(inc_wave.Text, 16);
                //var a =  BitsHelp.SetBitsToUint(XChipSnr.Find(f => f.NameType == "inc_wave_h").Bits, inc_wave.Text);
                //var b = (ulong)nHigh >> 8 & 0x03;
                //var c = BitsHelp.SetBitsToUint(XChipSnr.Find(f => f.NameType == "inc_wave_l").Bits, inc_wave.Text);
                //var d = (ulong)nHigh & 0xff;
                //var g = (ulong)~c;
                //var h = (ulong)~a;
                //SetSNRRegister("inc_wave_h", (ulong)nHigh>>8&0x03);
                //SetSNRRegister("inc_wave_l", (ulong)nHigh&0xff);

                if (XChipHelp.XChipSnr.Exists(c => c.NameType.ToLower() == $"inc_wave_h".ToLower()))
                {
                    var model = XChipHelp.XChipSnr.Find(c => c.NameType.ToLower() == $"inc_wave_h".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, inc_wave.Text);
                    SetSNRRegister(model, Val);
                }
                if (XChipHelp.XChipSnr.Exists(c => c.NameType.ToLower() == $"inc_wave_l".ToLower()))
                {
                    var model = XChipHelp.XChipSnr.Find(c => c.NameType.ToLower() == $"inc_wave_l".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, inc_wave.Text);
                    SetSNRRegister(model, Val);
                }
            }
        }
        private void inc_wave_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            inc_wave_KeyDown(sender, keyEnter);
        }
        private void slope_k_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(slope_k.Text))
            {
                //var nHigh = Convert.ToUInt32(slope_k.Text, 16);
                //SetSNRRegister("slope_k", (ulong)nHigh & 0xff);
                if (XChipSnr.Exists(c => c.NameType.ToLower() == $"slope_k".ToLower()))
                {
                    var model = XChipSnr.Find(c => c.NameType.ToLower() == $"slope_k".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, slope_k.Text);
                    SetSNRRegister(model, Val);
                }
            }
        }

        private void slope_k_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            slope_k_KeyDown(sender, keyEnter);
        }

        private void slope_b_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(slope_b.Text))
            {
                //var nHigh = Convert.ToUInt32(slope_b.Text, 16);
                //SetSNRRegister("slope_b", (ulong)nHigh & 0xff);
                if (XChipSnr.Exists(c => c.NameType.ToLower() == $"slope_b".ToLower()))
                {
                    var model = XChipSnr.Find(c => c.NameType.ToLower() == $"slope_b".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, slope_b.Text);
                    SetSNRRegister(model, Val);
                }
            }
        }

        private void slope_b_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            slope_b_KeyDown(sender, keyEnter);
        }

        private void offset_k_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(offset_k.Text))
            {
                //var nHigh = Convert.ToUInt32(offset_k.Text, 16);
                //SetSNRRegister("offset_k", (ulong)nHigh & 0xff);
                if (XChipSnr.Exists(c => c.NameType.ToLower() == $"offset_k".ToLower()))
                {
                    var model = XChipSnr.Find(c => c.NameType.ToLower() == $"offset_k".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, offset_k.Text);
                    SetSNRRegister(model, Val);
                }
            }
        }

        private void offset_k_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            offset_k_KeyDown(sender, keyEnter);
        }

        private void offset_b_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(offset_b.Text))
            {
                //var nHigh = Convert.ToUInt32(offset_b.Text, 16);
                //SetSNRRegister("offset_b", (ulong)nHigh & 0xff);
                if (XChipSnr.Exists(c => c.NameType.ToLower() == $"offset_b".ToLower()))
                {
                    var model = XChipSnr.Find(c => c.NameType.ToLower() == $"offset_b".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, offset_b.Text);
                    SetSNRRegister(model, Val);
                }
            }
        }

        private void offset_b_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            offset_b_KeyDown(sender, keyEnter);
        }

        private void scale_sigma_p_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_sigma_p.Text))
            {
                //var nHigh = Convert.ToUInt32(scale_sigma_p.Text, 16);
                //SetSNRRegister("scale_sigma_p", (ulong)nHigh & 0xff);
                if (XChipSnr.Exists(c => c.NameType.ToLower() == $"scale_sigma_p".ToLower()))
                {
                    var model = XChipSnr.Find(c => c.NameType.ToLower() == $"scale_sigma_p".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_sigma_p.Text);
                    SetSNRRegister(model, Val);
                }
            }
        }

        private void scale_sigma_p_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_sigma_p_KeyDown(sender, keyEnter);
        }

        private void scale_sigma_b_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_sigma_b.Text))
            {
                //var nHigh = Convert.ToUInt32(scale_sigma_b.Text, 16);
                //SetSNRRegister("scale_sigma_b", (ulong)nHigh & 0xff);
                if (XChipSnr.Exists(c => c.NameType.ToLower() == $"scale_sigma_b".ToLower()))
                {
                    var model = XChipSnr.Find(c => c.NameType.ToLower() == $"scale_sigma_b".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_sigma_b.Text);
                    SetSNRRegister(model, Val);
                }
            }
        }

        private void scale_sigma_b_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_sigma_b_KeyDown(sender, keyEnter);
        }

        private void scale_sigma_d_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_sigma_d.Text))
            {
                //var nHigh = Convert.ToUInt32(scale_sigma_d.Text, 16);
                //SetSNRRegister("scale_sigma_d", (ulong)nHigh & 0xff);
                if (XChipSnr.Exists(c => c.NameType.ToLower() == $"scale_sigma_d".ToLower()))
                {
                    var model = XChipSnr.Find(c => c.NameType.ToLower() == $"scale_sigma_d".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_sigma_d.Text);
                    SetSNRRegister(model, Val);
                }
            }
        }

        private void scale_sigma_d_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_sigma_d_KeyDown(sender, keyEnter);
        }

        private void weight_center_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(weight_center.Text))
            {
                //var nHigh = Convert.ToUInt32(weight_center.Text, 16);
                //SetSNRRegister("weight_center", (ulong)nHigh & 0xff);
                //下发dnr寄存器
                if (XChipDnr.Exists(c => c.NameType.ToLower() == "Raw_Gsl5".ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == "Raw_Gsl5".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, weight_center.Text);
                    SetSNRRegister(model, Val);
                }
                if (XChipDnr.Exists(c => c.NameType.ToLower() == "Raw_Gsl6".ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == "Raw_Gsl6".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, weight_center.Text);
                    SetSNRRegister(model, Val);
                }
                if (XChipDnr.Exists(c => c.NameType.ToLower() == "Raw_Gsl7".ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == "Raw_Gsl7".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, weight_center.Text);
                    SetSNRRegister(model, Val);
                }
                if (XChipDnr.Exists(c => c.NameType.ToLower() == "Raw_Gsl8".ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == "Raw_Gsl8".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, weight_center.Text);
                    SetSNRRegister(model, Val);
                }
                if (XChipDnr.Exists(c => c.NameType.ToLower() == "Raw_Gsl9".ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == "Raw_Gsl9".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, weight_center.Text);
                    SetSNRRegister(model, Val);
                }
                if (XChipSnr.Exists(c => c.NameType.ToLower() == $"weight_center".ToLower()))
                {
                    var model = XChipSnr.Find(c => c.NameType.ToLower() == $"weight_center".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, weight_center.Text);
                    SetSNRRegister(model, Val);
                }
            }
        }

        private void weight_center_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            weight_center_KeyDown(sender, keyEnter);
        }

        private void scale_sigma_man_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_sigma_man.Text))
            {
                //var nHigh = Convert.ToUInt32(scale_sigma_man.Text, 16);
                //SetSNRRegister("scale_sigma_man", (ulong)nHigh & 0xff);
                if (XChipSnr.Exists(c => c.NameType.ToLower() == $"scale_sigma_man".ToLower()))
                {
                    var model = XChipSnr.Find(c => c.NameType.ToLower() == $"scale_sigma_man".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_sigma_man.Text);
                    SetSNRRegister(model, Val);
                }
            }
        }

        private void scale_sigma_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_sigma_man_KeyDown(sender, keyEnter);
        }

        private void scale_nr_man_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_nr_man.Text))
            {
                //var nHigh = Convert.ToUInt32(scale_nr_man.Text, 16);
                //SetSNRRegister("scale_nr_man", (ulong)nHigh & 0xff);
                if (XChipSnr.Exists(c => c.NameType.ToLower() == $"scale_nr_man".ToLower()))
                {
                    var model = XChipSnr.Find(c => c.NameType.ToLower() == $"scale_nr_man".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_nr_man.Text);
                    SetSNRRegister(model, Val);
                }
            }
        }

        private void scale_nr_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_nr_man_KeyDown(sender, keyEnter);
        }

        private void scale_sigma_man_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            //var readVal = GetSNRRegister("scale_sigma_man_en");
            //SetSNRRegister("scale_sigma_man_en", (ulong)(scale_sigma_man_en.Checked ? (readVal | 0x01) : (readVal & 0xfe)));
            if (XChipSnr.Exists(c => c.NameType.ToLower() == $"scale_sigma_man_en".ToLower()))
            {
                var model = XChipSnr.Find(c => c.NameType.ToLower() == $"scale_sigma_man_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), scale_sigma_man_en.Checked);
                SetSNRRegister(model, Val);
            }
        }

        private void scale_nr_man_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            //var readVal = GetSNRRegister("scale_nr_man_en");
            //SetSNRRegister("scale_nr_man_en", (ulong)(scale_nr_man_en.Checked ? (readVal | 0x01) : (readVal & 0xfe)));
            if (XChipSnr.Exists(c => c.NameType.ToLower() == $"scale_nr_man_en".ToLower()))
            {
                var model = XChipSnr.Find(c => c.NameType.ToLower() == $"scale_nr_man_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), scale_nr_man_en.Checked);
                SetSNRRegister(model, Val);
            }
        }

        private void scale_sigma_list_0_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Enter)
            {
                if (isWrite) return;
                var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txtEdit.Text)) return;
                //SetSNRRegister($"scale_sigma_list[{txtEdit.Tag.ToString()}]", (ulong)Convert.ToInt32(txtEdit.Text, 16));
                if (XChipSnr.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
                {
                    var model = XChipSnr.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                    SetSNRRegister(model, Val);
                }
            }
           
        }

        private void scale_sigma_list_0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_sigma_list_0_KeyDown(sender, keyEnter);
        }

        private void scale_nr_list_0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (isWrite) return;
                var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txtEdit.Text)) return;
                //SetSNRRegister($"scale_nr_list[{txtEdit.Tag.ToString()}]", (ulong)Convert.ToInt32(txtEdit.Text, 16));
                if (XChipSnr.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
                {
                    var model = XChipSnr.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                    SetSNRRegister(model, Val);
                }
            }
            

        }

        private void scale_nr_list_0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_nr_list_0_KeyDown(sender, keyEnter);
        }

        private void scale_sigma_actv_0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (isWrite) return;
                var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txtEdit.Text)) return;
                //SetSNRRegister($"scale_sigma_actv[{txtEdit.Tag.ToString()}]", (ulong)Convert.ToInt32(txtEdit.Text, 16));
                if (XChipSnr.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
                {
                    var model = XChipSnr.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                    SetSNRRegister(model, Val);
                }
            }
        }

        private void scale_sigma_actv_0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_sigma_actv_0_KeyDown(sender, keyEnter);
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton5_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            isRead = true;
            WaitBefore.Start("读取中", "正在加载中", 10);
            //string nameType = string.Empty;
            //for (int i = 0; i < XChipSnr.Count; i++)
            //{
            //    var type = AppHelper.NameTypeToString(XChipSnr[i].NameType);
            //    //加上单选框的_en
            //    if (XChipSnr[i].ControlType == "1")
            //    {
            //        type = XChipSnr[i].NameType;
            //    }
            //    try
            //    {
            //        //if (type.Contains("inc"))
            //        //{

            //        //}
            //        Control col = this.Controls.Find(type, true)[0];
            //        if (nameType == type) continue;
            //        nameType = type;

            //        if (col is TextEdit)
            //        {
            //            //过滤掉指定寄存器
            //            if (listfiltration.Exists(c => c == col.Name.ToString()))
            //            {
            //                continue;
            //            }
            //            var nameList = XChipSnr.Where(c => c.NameType.ToLower().Contains(type)).ToList();
            //            long tempU = 0;
            //            foreach (var nitem in nameList)
            //            {
            //                tempU += GetSNRRegister(nitem.NameType);
            //            }
            //            col.Text = tempU.ToString("X");
            //        }
            //        else if (col is CheckEdit)
            //        {
            //            (col as CheckEdit).Checked = (GetSNRRegister(type) == 0);
            //        }
            //    }
            //    catch (Exception)
            //    {
            //        continue;
            //    }
            //}

            List<string> NameList = new List<string>();

            for (int i = 0; i < XChipSnr.Count; i++)
            {
                if (XChipSnr[i].NameType.Contains("enh_en"))
                {

                }
                var type = AppHelper.NameTypeToString(XChipSnr[i].NameType);
                if (NameList.Exists(c => c.ToLower() == (type)))
                {
                    continue;
                }
                //加上单选框的_en
                if (XChipSnr[i].ControlType == "1")
                {
                    type = XChipSnr[i].NameType;
                }
                var col = Controls_Find(type);

                foreach (var item in col)
                {
                    if (item is TextEdit)
                    {

                        var nList = XChipSnr.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                        if (nList.Count == 0)
                        {
                            nList = XChipSnr.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                        }
                        if (nList.Count == 1)
                        {
                            var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                            item.Text = BitsHelp.GetBitsToUint(nList[0].Bits, nList[0].Hex, Val).ToString("X");
                        }
                        else
                        {
                            string Val = string.Empty;
                            //这里默认为是有多个寄存器  一个文本框的情况进行处理
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_h")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_h")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m2")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m0")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m1")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m1")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m0")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m2")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                            {
                                if (nList.Exists(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                }
                                else
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Last(c => c.NameType.ToLower().Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                }
                            }

                            item.Text = Val;
                        }
                    }
                    else if (item is CheckEdit)
                    {
                        var nList = XChipSnr.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                        if (nList.Count == 1)
                        {
                            var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                            (item as CheckEdit).Checked = BitsHelp.GetBitsCheckedToBool(nList[0].Bits, nList[0].Hex, Val) == 0;
                        }
                    }
                    NameList.Add(item.Name);

                }

                //NameList.Add(type);
            }
            isRead = false;
            WaitBefore.Close();

        }
        private Control[] Controls_Find(string str)
        {
            //var t =   this.Controls.Find(type, true);
            List<Control> listc = new List<Control>();
            System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            for (int i = 0; i < fieldInfo.Length; i++)
            {
                if (fieldInfo[i].Name.ToLower().Contains(str.ToLower()))
                {
                    listc.AddRange(this.Controls.Find(fieldInfo[i].Name, true));
                    //break;
                }
            }
            return listc.ToArray();
        }

        public void Get_SlopeOffsetSigmaNr() {
            slope.Text = GetSNRRegister("slope").ToString("X2");
            offset.Text = (GetSNRRegister("offset_h") + GetSNRRegister("offset_l")).ToString("X4");
            scale_sigma.Text = GetSNRRegister("scale_sigma").ToString("X2");
            scale_nr.Text = GetSNRRegister("scale_nr").ToString("X2");
            
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            Get_SlopeOffsetSigmaNr();
        }

        private void btn_SaveISPSetting_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }

            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "配置文件（*.txt）|*.txt";

            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "IQ_Setting_SNR_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                SerialSend.isDebug = false;
                StringBuilder sb = new StringBuilder();
                Pe_dal = new parameter_exportManager();
                if (null != Pe_dal)
                {
                    WaitBefore.Start("参数导出", "正在加载中", 60);
                    //var tempList = Pe_dal.GetList().OrderBy(c => c.SortNum);
                    var tempList = Pe_dal.GetList(c=> c.Module == "SNR").OrderBy(c => c.SortNum).ToList();
                    #region 判断是否需要用白天的数据
                    //var Pe_patch_dal = new parameter_export_patchManager();
                    //var patchList = Pe_patch_dal.GetList();
                    //var conditionList = tempList.Select(c => c.ConditionAddr).Distinct().ToList();
                    //foreach (var item in conditionList)
                    //{
                    //    if (SerialSend.ReadRegister(Convert.ToUInt32(item, 16), sPortTemp) == 0)
                    //    {
                    //        patchList.RemoveAll(c => c.ConditionAddr == item);
                    //    }
                    //}
                    #endregion
                    sb.Append("0xffff,0xfef1,\n");
                    sb.Append("\n");
                    sb.Append($"//{tempList.First().Module}\n");
                    foreach (var item in tempList)
                    {
                        try
                        {
                            sb.Append(string.IsNullOrEmpty(item.PreNote) ? "" : "\n" + item.PreNote + "\n");
                            sb.Append(string.IsNullOrEmpty(item.addr) ? "" : item.addr);
                            #region 判断是否需要用白天的数据
                            if (!string.IsNullOrEmpty(item.ReadAddr))
                            {
                                //if (patchList.Count != 0 && patchList.Select(c => c.ReadAddr).Contains(item.ReadAddr))
                                //{
                                //    sb.Append($",0x{SerialSend.ReadRegister((Convert.ToUInt32(item.RelationAddr.Trim(), 16)), sPortTemp).ToString("x2")},");
                                //}
                                //else
                                //{
                                    sb.Append($",0x{SerialSend.ReadRegister((Convert.ToUInt32(item.ReadAddr.Trim(), 16)), sPortTemp).ToString("x2")},");
                                //}
                            }
                            #endregion
                            sb.Append(string.IsNullOrEmpty(item.RearNote) ? "" : item.RearNote = item.RearNote.Replace("\\n", "\n").Replace("\\r", "\r"));
                            sb.Append("\n");
                        }
                        catch (Exception ex)
                        {
                            WaitBefore.Close();
                            //setShowMsg(item.RelationAddr);
                            DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                            return;
                        }
                    }
                    System.IO.File.WriteAllText(sfd.FileName, sb.ToString());
                    WaitBefore.Close();
                    DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
                }
            }
            SerialSend.isDebug = true;
        }

        private void weight_s4_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            //var readVal = GetSNRRegister("weight_s4");
            //SetSNRRegister("weight_s4", (ulong)(weight_s4.Checked ? 0x1 : 0x0));
            if (XChipSnr.Exists(c => c.NameType.ToLower() == $"weight_s4_en".ToLower()))
            {
                var model = XChipSnr.Find(c => c.NameType.ToLower() == $"weight_s4_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), weight_s4_en.Checked);
                SetSNRRegister(model, Val);
            }

        }

        private void tunning_disp_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;

            if (XChipSnr.Exists(c => c.NameType.ToLower() == $"{tunning_en.Name}".ToLower()))
            {
                var model = XChipSnr.Find(c => c.NameType.ToLower() == $"{tunning_en.Name}".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), tunning_en.Checked);
                SetSNRRegister(model, Val);
            }
            
            Mode_switch.Enabled = tunning_en.Checked;
            Mode_switch.SelectedIndex = 0;

        }

        private void Mode_switch_SelectedIndexChanged(object sender, EventArgs e)
        {


            if (isWrite) return;
            
            if (XChipSnr.Exists(c => c.NameType.ToLower() == "tunning_branch".ToLower()))
            {
                var model = XChipSnr.Find(c => c.NameType.ToLower() == "tunning_branch".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Mode_switch.SelectedIndex.ToString());
                SetSNRRegister(model, Val);
            }
            if (XChipSnr.Exists(c => c.NameType.ToLower() == $"{tunning_en.Name}".ToLower()))
            {
                var model = XChipSnr.Find(c => c.NameType.ToLower() == $"{tunning_en.Name}".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), tunning_en.Checked);
                SetSNRRegister(model, Val);
            }
        }

        private void scale_sigma_list4_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_sigma_list4_KeyDown(sender, keyEnter);
        }

        private void scale_sigma_list4_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (isWrite) return;
                var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txtEdit.Text)) return;
                //下发dnr寄存器
                if (XChipDnr.Exists(c => c.NameType.ToLower() == "Raw_Rbsl5".ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == "Raw_Rbsl5".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                    SetSNRRegister(model, Val);
                }
                if (XChipDnr.Exists(c => c.NameType.ToLower() == "Raw_Rbsl6".ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == "Raw_Rbsl6".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                    SetSNRRegister(model, Val);
                }
                if (XChipDnr.Exists(c => c.NameType.ToLower() == "Raw_Rbsl7".ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == "Raw_Rbsl7".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                    SetSNRRegister(model, Val);
                }
                if (XChipDnr.Exists(c => c.NameType.ToLower() == "Raw_Rbsl8".ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == "Raw_Rbsl8".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                    SetSNRRegister(model, Val);
                }
                if (XChipDnr.Exists(c => c.NameType.ToLower() == "Raw_Rbsl9".ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == "Raw_Rbsl9".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                    SetSNRRegister(model, Val);
                }
                //SetSNRRegister($"scale_sigma_list[{txtEdit.Tag.ToString()}]", (ulong)Convert.ToInt32(txtEdit.Text, 16));
                if (XChipSnr.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
                {
                    var model = XChipSnr.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                    SetSNRRegister(model, Val);
                }
            }
        }
    }



}
